const DB = require('../tools/mysql')

module.exports = async ctx => {

  const { filename, description, table } = ctx.req.body,
    id = ctx.query.id

  let tablename = ''
  switch (table) {
    case '0':
      tablename = 'village_registry'
      break
    case '1':
      tablename = 'home_registy'
      break
    case '2':
      tablename = 'three_implementation'
      break
    case '3':
      tablename = 'issue_list'
      break
    default:
      tablename = 'village_registry'
  }

  const [fileId] = await DB('files').insert({
    name: filename,
    src: `/files/${id}/${filename}`,
    description,
    time: new Date()
  })

  const [{ files }] = await DB(tablename).select('files').where('id', id)

  let fileList = files ? files.split(',') : []
  fileList.push(fileId)

  const data = await DB(tablename).update('files', fileList.join(',')).where('id', id)
  if (data === 1) {
    ctx.body = { code: 1, msg: '图片保存成功' }
  } else {
    ctx.body = { code: 0, msg: '图片保存失败' }
  }

}